package net;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * @Author Justin Parker
 * @Date 2024/7/19 0019 17:24
 * @Version 1.0
 */
public class MapThreadChatServer {
    private ServerSocket serverSocket;
    //构建一个集合对象，存储所有客户端的输出流对象
//    private List<PrintWriter> allOut = new ArrayList<>();
    //构建一个集合对象，存储所有用户昵称和客户端的输出流对象
    private Map<String,PrintWriter> allOut = new HashMap<>();
    private static final int PORT;

    static {
        PORT = 8088;
    }

    public MapThreadChatServer() {
        try {
            System.out.println("服务器开始启动.....");
            serverSocket = new ServerSocket(PORT);
            System.out.println("服务器启动成功,正在" + PORT + "端口监听中.....");
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("服务器启动失败！");
            System.exit(-1);
        }
    }

    private class ClientHandler implements Runnable {
        private Socket socket;
        private String host;
        private String toNickName ;

        public ClientHandler(Socket socket) {
            this.socket = socket;
            host = this.socket.getInetAddress().getHostName();
        }

        public void run() {
            PrintWriter pw = null;

            try {
                BufferedReader br = new BufferedReader(
                        new InputStreamReader(
                                socket.getInputStream(), StandardCharsets.UTF_8));

                 pw = new PrintWriter(
                        new BufferedWriter(
                                new OutputStreamWriter(
                                        socket.getOutputStream(),
                                        StandardCharsets.UTF_8)), true);
                //将每个线程的输出流对象加入到集合中
                toNickName = br.readLine();

                synchronized (allOut){
                    allOut.put(toNickName,pw);
                }
                //发消息给所有客户端，告知谁上线了
                sendMessageToAllClient(toNickName+"上线了");
                //3.通过此对象读取数据
                String line = null;
                while ((line = br.readLine()) != null) {
                    System.out.println(host + "客户端读取的信息：" + line);
                    if (line.startsWith("@")||line.startsWith("$")||line.startsWith("#")){
                        //给某个人发消息
                        sendMessageToOneClient(line);
                    }else {
                        //发送消息给所有客户端
                        sendMessageToAllClient(line);

                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            finally {
                try{
                    synchronized (allOut){
                    //allOut.remove(nikeName);
                    }
                    socket.close();
                    System.out.println("客户端断开连接！");
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
        }
        //发消息给指定用户,消息格式：@nikeName:msg
        private void sendMessageToOneClient(String line){
            //获取msg内容
            String msg = line.substring(line.indexOf(":")+1);
            //获取nikeName
            String toNikeName = line.substring(1, line.indexOf(":"));
            //给nikeName发消息
            if (allOut.containsKey(toNickName)){
                allOut.get(toNickName).println(host+"说:"+msg);
            }else {
                sendMessageToAllClient(toNickName+"用户已下线");
            }
        }
        //发消息给所有用户
        private void sendMessageToAllClient(String line){
            System.out.println("client msg:" + line);
            synchronized (allOut){
                //迭代所有的输出流对象
                Collection<PrintWriter> values = allOut.values();
                for (PrintWriter out : values){
                    out.println( host + "客户端发送的数据：" + line);
                }
            }
        }
    }

    //启动服务读取数据
    public void start() {
        while (true) {
            try {
                Socket socket = serverSocket.accept();
                System.out.println("客户端连接成功！");

                new Thread(new ClientHandler(socket)).start();

            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }


    public static void main(String[] args) {
        new MapThreadChatServer().start();
    }
}

